/**
 * 作者：陈文斌 on 2019/1/3.
 * 邮箱：chen_wennbin@163.com
 * 版本：v1.0
 */

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'shared_preferences_util.dart';
import 'package:crm/constant/api.dart';

class ApolloRequestUtil {
  /// 判断账号是否设置密码
  static void isInitPassword(
    Function callback, {
    Map args,
    Function errorCallback,
  }) {
    var query = """
      query{
        checkStatus{
          isInitPassword
        }
      }
    """;
    QueryUtil queryUtil = QueryUtil(
      url: JavaApi.jwtAuthServer,
      setQuery: query,
    );
    queryUtil.query(
      (response) {
        if (callback != null) {
          callback(response);
        }
      },
      errorCallback: (errMsg) {
        if (errorCallback != null) {
          errorCallback(errMsg);
        }
      },
    );
  }

  /// 发送短信验证码
  static void sendSms(
    Function callback, {
    Map args,
    Function errorCallback,
  }) async {
    var query = """
      mutation sendSms(\$args: SendSMSDataInput!){
        sendSms(args:\$args){
          RealName,
          phoneNumber,
        }
      }
    """;

    QueryUtil queryUtil = QueryUtil(
      url: JavaApi.jwtAuthServer,
      setQuery: query,
      setArgs: args,
    );
    queryUtil.query(
      (response) {
        if (callback != null) callback(response ?? '');
      },
      errorCallback: (errMsg) {
        if (errorCallback != null) errorCallback(errMsg ?? '');
      },
    );
  }

  /// 设置、重置CRM密码
  static void changePasswordQuery(
    Function callback, {
    Map args,
    Function errorCallback,
  }) async {
    var query = """
      mutation PasswordAOU(\$args: PasswordDataInput!){
          passwordAOU(args:\$args){
            passwordText
            passwordGesture
          }
        }
    """;

    QueryUtil queryUtil = QueryUtil(
      url: JavaApi.jwtAuthServer,
      setQuery: query,
      setArgs: args,
    );

    queryUtil.query(
      (response) {
        if (callback != null) callback(response);
      },
      errorCallback: (errMsg) {
        if (errorCallback != null) errorCallback(errMsg);
      },
    );
  }

  /// 查询所有客户信息
  static void customersSearch(
    Function callback, {
    Map args,
    Function errorCallback,
  }) async {
    var query = """
      query customersAll(\$args: CustomerSearchInput){
        customersAll(args:\$args){
          pageInfo{
            skip
            take
            total
            totalPage
          }
          items{
            id
            companyName
            phone
            location
            customerType
            streetaddress
            industryAttributes
            industryClassification
            creditLimit
            creditLimitUsed
            exdealDate
            exdealProbability
            salesMoney
            salesStage
            principals{
              principalEmployeeId
            }
            contacts{
              id
              name
              phone
              position
              QQaccount
              mail
              telephone
            }
          }
        }
      }
    """;

    QueryUtil queryUtil = QueryUtil(
      url: JavaApi.crmServer,
      setQuery: query,
      setArgs: args,
    );

    queryUtil.query(
      (response) {
        if (callback != null) callback(response);
      },
      errorCallback: (errMsg) {
        if (errorCallback != null) errorCallback(errMsg);
      },
    );
  }

  /// 添加、修改客户
  static void customerAOU(
    Function callback, {
    Map args,
    Function errorCallback,
  }) {
    var query = """
      mutation customerAOU(\$args:CustomerDataInput!){
        customerAOU(args:\$args){
          id
          contacts{
            name
          }
        }
      }
    """;
    QueryUtil queryUtil = QueryUtil(
      url: JavaApi.crmServer,
      setQuery: query,
      setArgs: args,
    );

    queryUtil.query((response) {
      if (callback != null) {
        callback(response);
      }
    }, errorCallback: (errMsg) {
      if (errorCallback != null) {
        errorCallback(errMsg);
      }
    });
  }

  /// 查询访问记录、查看访问详情
  static void searchVisitor(
    Function callback, {
    Map args,
    Function errorCallback,
  }) {
    var query = """
      query (\$args: VisitorSearchInput!){
        crmVisitors(args:\$args){
          items{
            id
            visitorEmployeeId
            visitorType
            visitorTime
            visitorAddress
            visitorDetails
            visitorImages{
              imageUrl
            }
            customerId
            types{
              code
              content
            }
            customer{
              companyName
            }
          }
        }
      }
    """;

    QueryUtil queryUtil = QueryUtil(
      url: JavaApi.crmServer,
      setQuery: query,
      setArgs: args,
    );
    queryUtil.query(
      (response) {
        if (callback != null) {
          callback(response);
        }
      },
      errorCallback: (errMsg) {
        if (errorCallback != null) {
          errorCallback(errMsg);
        }
      },
    );
  }

  /// 查询拜访类型
  static void visitorTypes(
    Function callback, {
    Map args,
    Function errorCallback,
  }) {
    var query = """
      query visitorTypes(\$args: SearchBeanInput){
        visitorTypes(args:\$args){
          items{
            id
           code
            content
          }
        }
      }
    """;
    QueryUtil queryUtil =
        QueryUtil(url: JavaApi.crmServer, setQuery: query, setArgs: args);
    queryUtil.query((response) {
      if (callback != null) {
        callback(response);
      }
    }, errorCallback: (errMsg) {
      if (errorCallback != null) {
        errorCallback(errMsg);
      }
    });
  }

  /// 查询用户反馈记录
  static void searchFeedbackRecord(
    Function callback, {
    Map args,
    Function errorCallback,
  }) {
    var query = """
      query (\$args:ByCustomerSearchInput){
        feedbacks(args:\$args){
          items{
            id
            details
            images{
              imageName
              imageUrl
            }
            customer{
              companyName
              phone
            }
            receiver
            recordTime
            processingStatus
            feedbackProcesss{	
              images{
                imageName
                imageUrl
              }
              details
            }
          }
        }
      }
    """;

    QueryUtil queryUtil = QueryUtil(
      url: JavaApi.crmServer,
      setQuery: query,
      setArgs: args,
    );
    queryUtil.query(
      (response) {
        if (callback != null) {
          callback(response);
        }
      },
      errorCallback: (errMsg) {
        if (errorCallback != null) {
          errorCallback(errMsg);
        }
      },
    );
  }

  /// 查询用户痛点记录
  static void searchPainPointRecord(
    Function callback, {
    Map args,
    Function errorCallback,
  }) {
    var query = """
      query painPoints(\$args: ByCustomerSearchInput){
        painPoints(args:\$args){
          items{
            details
            images{
              imageName
              imageUrl
            }
            customer{
              companyName
            }
            recorder
            recordtime
            id
          }
        }
      }
    """;

    QueryUtil queryUtil = QueryUtil(
      url: JavaApi.crmServer,
      setQuery: query,
      setArgs: args,
    );
    queryUtil.query(
      (response) {
        if (callback != null) {
          callback(response);
        }
      },
      errorCallback: (errMsg) {
        if (errorCallback != null) {
          errorCallback(errMsg);
        }
      },
    );
  }
}

class QueryUtil {
  final String url;
  final String setQuery;
  final Map setArgs;
  final Map setVariables;

  QueryUtil({
    this.url,
    this.setQuery,
    this.setArgs,
    this.setVariables,
  });

  void query(
    Function callback, {
    Map<String, String> headers,
    Function errorCallback,
    bool isCarryCookie = true,
  }) async {
    // 设置variables
    var variables = setVariables ?? {};
    if (setArgs != null && setArgs.isNotEmpty) {
      variables = {'args': setArgs};
    }

    // 设置data
    var params = {
      'query': setQuery,
      'variables': variables,
    };

    await _request(
      url,
      callback,
      method: 'post',
      headers: headers,
      params: params,
      errorCallback: errorCallback,
      isCarryCookie: isCarryCookie,
    );
  }

  static Future _request(
    String url,
    Function callback, {
    String method,
    Map<String, String> headers,
    params,
    Function errorCallback,
    bool isCarryCookie,
  }) async {
    try {
      Map<String, String> headerMap = headers == null ? new Map() : headers;
      var paramMap = params == null ? new Map() : params;

      headerMap['Content-type'] = 'application/json';
      if (isCarryCookie && SpUtil.getString('Cookies') != null) {
        headerMap['Cookie'] = SpUtil.getString('Cookies');
      }

      var client = new http.Client();

      client
          .post(
        Uri.parse(url),
        headers: headerMap,
        body: json.encoder.convert(paramMap),
      )
          .then((http.Response r) {
        print('${r.request.url} ,method=${r.request.method}');
        if (r.request.method == 'POST') {
          print('请求参数：${jsonEncode(paramMap)}');
        }
        print('响应内容:code=${r.statusCode} size=${r.contentLength},${r.body}');
        _dataDetection(r, callback, errorCallback);
      });
    } catch (exception) {
      _handError(errorCallback, exception.toString());
    }
  }

  static void _dataDetection(http.Response r, callback, errorCallback) {
    if (r.statusCode != 200) {
      if (jsonDecode(r.body) is Map) {
        _handError(errorCallback, jsonDecode(r.body)['Message']);
      } else {
        _handError(errorCallback, jsonDecode(r.body));
      }
      return;
    }

    // 请求成功
    // cookies处理
    String cookies = r.headers['set-cookie'];
    if (cookies != null) {
      SpUtil.putString('Cookies', cookies);
    }
    if (callback != null) {
      callback(json.decoder.convert(utf8.decoder.convert(r.bodyBytes)));
    }
  }

  static void _handError(Function errorCallback, String errorMsg) {
    if (errorCallback != null) {
      errorCallback(errorMsg);
    }
  }
}
